package chapter1.zyq1_str_obj;

import java.net.InetSocketAddress;
import java.net.Socket;

public class Client3 {
    public static void main(String[] args) {
        /*ExecutorService fixPool = Executors.newCachedThreadPool();
        int concurrentCount = 10;
        //用多线程模拟多客户端并发通信
        for (int i=0;i<concurrentCount;i++) {
            fixPool.execute(
                    ()->{
                        Client3 client = new Client3();
                        client.communicate();
                    }
            );
        }
        fixPool.shutdown();*/
        Client3 client = new Client3();
        client.communicate();
    }

    public void communicate() {
        InetSocketAddress isAddr = new InetSocketAddress("localhost", 8002);
        Socket socket = new Socket();
        try {
            //设置客户端的连接超时为30000毫秒
            socket.connect(isAddr , 30000 );
            System.out.println("客户端连接成功，开始会话...");
            //设置客户端的读超时为20000毫秒
            socket.setSoTimeout(20000);
            session(socket);
            socket.close();
            System.out.println("会话结束，客户端关闭连接。");
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    protected void session(Socket socket) throws Exception {
        String msg = "How are you!";
        System.out.println("Send: " + msg);
        sendReceiveUtil_Str23.sendString(socket, msg);
        Thread.sleep(900);

        msg = sendReceiveUtil_Str23.recvString(socket);
        System.out.println("Receive: " + msg);
        msg = sendReceiveUtil_Str23.recvString(socket);
        System.out.println("Receive: " + msg);
        Thread.sleep(900);

        msg = "I'm fine too.";
        sendReceiveUtil_Str23.sendString(socket, msg);
        System.out.println("Send: " + msg);
        Thread.sleep(900);
    }
}
